<template>
  <view class="container disFlexCol gap-10">
    <OperationCard
      v-for="(item, index) in editBusinessOpportunitiesDetail"
      :key="item.id"
      :index="index"
      :length="editBusinessOpportunitiesDetail.length"
      :boType="boType"
      v-model:module="editBusinessOpportunitiesDetail[index]"
      @top="moveUp(index)"
      @down="moveDown(index)"
      @topping="moveTopping(index)"
      @delete="showDelModal(index)"
      @add="handleAdd(index)"
    ></OperationCard>
    <view class="p-12 bgf br-8">
      <view v-if="isComponent" class="disFlxJC">
        <text class="fz-14">+ 添加模块</text>
      </view>
      <view class="w-full h-1 mt-8 mb-8" style="background-color: #ebedf0"></view>
      <view class="grid grid-col-4">
        <view class="h-64 disFlxCC" @click="addModel(ModuleTypeEnum.LargeImage)">
          <text class="ali-icon icon-tupian fz-24"></text>
          <text class="fz-14">大图</text>
        </view>
        <view class="h-64 disFlxCC" @click="addModel(ModuleTypeEnum.SmallImage)">
          <text class="ali-icon icon-gongge fz-24"></text>
          <text class="fz-14">小图</text>
        </view>
        <view class="h-64 disFlxCC" @click="addModel(ModuleTypeEnum.Video)">
          <text class="ali-icon icon-shexiangji fz-24"></text>
          <text class="fz-14">视频</text>
        </view>
        <view class="h-64 disFlxCC" @click="addModel(ModuleTypeEnum.Text)">
          <text class="ali-icon icon-title fz-24"></text>
          <text class="fz-14">文字</text>
        </view>
      </view>
    </view>
  </view>

  <ActionSheet
    v-model="showActionSheet"
    :itemList="actionSheetitemList"
    @change="handleShowActionSheetChange"
  ></ActionSheet>
</template>

<script lang="ts" setup>
  import OperationCard from './OperationCard.vue';
  import { useUpload } from '@/hooks/core/useUpload';
  import { onLoad } from '@/router';
  import { onMounted, ref, watch } from 'vue';
  import {
    ModuleTypeEnum,
    type IEditBusinessOpportunitiesDetailEnum,
  } from '@/enums/editBusinessOpportunitiesDetailEnum';

  import ActionSheet, { type ActionSheetItem } from '@/components/ActionSheet/index.vue';
  import type { EditBusinessOpportunitiesDetail } from '@/router/types/modules';
  import type { BoTypeEnum } from '@/enums/businessOpportunitiesEnum';

  const editBusinessOpportunitiesDetail = ref<IEditBusinessOpportunitiesDetailEnum[]>([]);

  const isComponent = ref(false);

  const emits = defineEmits(['loadingComplete']);
  onMounted(() => {
    emits('loadingComplete');
  });

  const boType = ref();

  const setData = (op: EditBusinessOpportunitiesDetail) => {
    isComponent.value = !!op.successFn;
    boType.value = op.boType;

    const productDescStr = op.editBusinessOpportunitiesDetail;

    if (!productDescStr) {
      addModel(ModuleTypeEnum.Text);
      return;
    }
    editBusinessOpportunitiesDetail.value = JSON.parse(
      productDescStr,
    ) as IEditBusinessOpportunitiesDetailEnum[];
  };

  const showActionSheet = ref(false);
  const actionSheetitemList = ref<ActionSheetItem[]>([
    {
      icon: 'ali-icon icon-tupian',
      text: '向下添加大图',
    },
    {
      icon: 'ali-icon icon-gongge',
      text: '向下添加小图',
    },
    {
      icon: 'ali-icon icon-shexiangji',
      text: '向下添加视频',
    },
    {
      icon: 'ali-icon icon-title',
      text: '向下添加文字',
    },
  ]);

  function handleShowActionSheetChange(index: number) {
    switch (index) {
      case 0:
        addModel(ModuleTypeEnum.LargeImage, currIndex.value + 1);
        break;
      case 1:
        addModel(ModuleTypeEnum.SmallImage, currIndex.value + 1);
        break;
      case 2:
        addModel(ModuleTypeEnum.Video, currIndex.value + 1);
        break;
      case 3:
        addModel(ModuleTypeEnum.Text, currIndex.value + 1);
        break;
    }
  }

  const currIndex = ref(-1);

  // 移动位置

  function moveUp(index: number): void {
    if (index <= 0 || index >= editBusinessOpportunitiesDetail.value.length) {
      return;
    }
    const element = editBusinessOpportunitiesDetail.value[index];
    editBusinessOpportunitiesDetail.value.splice(index, 1); // 移除元素
    editBusinessOpportunitiesDetail.value.splice(index - 1, 0, element); // 插入到上一个位置
  }

  function moveDown(index: number): void {
    if (index < 0 || index >= editBusinessOpportunitiesDetail.value.length - 1) {
      return;
    }
    const element = editBusinessOpportunitiesDetail.value[index];
    editBusinessOpportunitiesDetail.value.splice(index, 1); // 移除元素
    editBusinessOpportunitiesDetail.value.splice(index + 1, 0, element); // 插入到下一个位置
  }

  function moveTopping(index: number): void {
    if (index <= 0 || index >= editBusinessOpportunitiesDetail.value.length) {
      return;
    }
    const element = editBusinessOpportunitiesDetail.value[index];
    editBusinessOpportunitiesDetail.value.splice(index, 1); // 移除元素
    editBusinessOpportunitiesDetail.value.unshift(element); // 插入到数组开头
  }

  // 删除模块
  const currDelIndex = ref(-1);
  const showDelModal = (index: number) => {
    currDelIndex.value = index;
    uni.showModal({
      content: '确定删除该模块内容？',
      showCancel: true,
      confirmText: '确定',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          handleDelete();
        }
      },
    });
  };
  const handleDelete = () => {
    editBusinessOpportunitiesDetail.value.splice(currDelIndex.value, 1);
  };

  // 插入模块
  const handleAdd = (index: number) => {
    showActionSheet.value = true;
    currIndex.value = index;
  };

  const addModel = (type: number, insertAtIndex: number = -1) => {
    const upload = (count: number, mediaType: 'image' | 'video') => {
      const { chooseFile, successResult } = useUpload({ count });

      if (type == ModuleTypeEnum.Video || type == ModuleTypeEnum.SmallImage) {
        const desc = ref<IEditBusinessOpportunitiesDetailEnum>({
          moduleType: type,
          id: Date.now(),
        });
        let flag = true;
        let index = -1;
        const updateFileUrls = (newVal: string[]) => {
          if (index === -1) {
            desc.value.fileUrls = newVal;
          } else {
            editBusinessOpportunitiesDetail.value[index].fileUrls = newVal;
          }
        };
        watch(
          successResult,
          (newVal) => {
            updateFileUrls(newVal.map((item) => item.filePath!));

            if (!flag) return;
            flag = false;
            if (insertAtIndex === -1) {
              editBusinessOpportunitiesDetail.value.push(desc.value);
              index = editBusinessOpportunitiesDetail.value.length - 1;
            } else {
              editBusinessOpportunitiesDetail.value.splice(insertAtIndex, 0, desc.value);
              index = insertAtIndex;
            }

            showActionSheet.value = false;
          },
          { deep: true },
        );
      } else {
        watch(
          successResult,
          (newVal) => {
            const desc = ref<IEditBusinessOpportunitiesDetailEnum>({
              moduleType: type,
              id: Date.now(),
            });
            desc.value.fileUrls = [newVal.at(-1)!.filePath!];
            if (insertAtIndex === -1) {
              editBusinessOpportunitiesDetail.value.push(desc.value);
            } else {
              editBusinessOpportunitiesDetail.value.splice(insertAtIndex, 0, desc.value);
              insertAtIndex++;
            }

            showActionSheet.value = false;
          },
          { deep: true },
        );
      }

      return chooseFile({ mediaType });
    };

    // 添加图
    if (type == ModuleTypeEnum.LargeImage || type == ModuleTypeEnum.SmallImage) {
      return upload(9, 'image');
    }

    // 添加视频
    if (type == ModuleTypeEnum.Video) {
      return upload(1, 'video');
    }

    // 添加文本

    if (insertAtIndex == -1) {
      editBusinessOpportunitiesDetail.value.push({ moduleType: type, text: '', id: Date.now() });
    } else {
      editBusinessOpportunitiesDetail.value.splice(insertAtIndex, 0, {
        moduleType: type,
        text: '',
        id: Date.now(),
      });
    }
    showActionSheet.value = false;
  };

  const getData = () => {
    if (
      editBusinessOpportunitiesDetail.value.filter((item) => item.text || item.fileUrls?.length)
        .length
    ) {
      return JSON.stringify(editBusinessOpportunitiesDetail.value);
    } else {
      return '';
    }
  };

  const updateBoType = (newBoType: BoTypeEnum) => {
    boType.value = newBoType;
  };
  defineExpose({
    getData,
    setData,
    updateBoType,
  });
</script>

<style lang="scss" scoped></style>
